<?php
namespace cubox\provider;
use cubox\Cubox;
trait PDO{
    protected $connection;
    protected $inTransaction = false;
    protected static $sqlList = [];
    public function __construct(array $config){
        if(!extension_loaded('pdo')){
            throw new \Exception('The PDO extension is not loaded.');
        }

        $dns = '';
        switch(strtolower($config['driver'])){
            case 'mysql':
                $host = $config['host'];

                if (isset($config['port']) && $config['port'] != '') $host = $config['host'].':'.$config['port'];
                $dns = 'mysql:host='.$host.';dbname='.$config['database'].';charset=utf8';
                
                break;
            case 'sqlite':
                $dns = 'sqlite:'.$config['database'];
                 
                break;
            case 'mssql':
                $host = $config['host'];
                if (isset($config['port']) && $config['port'] != '') $host = $config['host'].','.$config['port'];
                $dns = 'sqlsrv:server='.$host.';Database ='.$config['database'];
            break;
            default:
                throw new \Exception('The PDO driver is not supported.');
                break;
        }
        
        try{

            if (!isset($config['user'])) $config['user'] = '';
            if (!isset($config['password'])) $config['password'] = '';

            $this->connection = new \PDO($dns,$config['user'],$config['password']);

        }catch(\PDOException $e){
            throw new \Exception('The PDO connection failed');
        }

        parent::__construct($config);
    }


    public function query($sql){

        Cubox::debug($sql);
        self::$sqlList[] =  $sql;

        try{
            $time  = microtime(true);
            $statement  = $this->connection->query($sql);
            
            $time = round(microtime(true) - $time,3);
            
            if ( $time> 3){
                Cubox::log('LONG QUERY '.$time.':'.$sql);
            }

            return $statement->fetchAll( \PDO::FETCH_ASSOC);
        }catch(\PDOException $e){
            throw new \Exception('The PDO query failed: '.$e->getMessage());
        }
    }



    public function getInsertId():int{
        return (int) $this->connection->lastInsertId();
    }

    public function beginTransaction(){
        $this->connection->beginTransaction();
        $this->inTransaction = true;
    }

    public function commit(){
        if ($this->inTransaction){
            $this->connection->commit();
            $this->inTransaction = false;
        }
    }

    public function rollBack(){
        if ($this->inTransaction){
            $this->connection->rollBack();
            $this->inTransaction = false;
        }
    }
}